//
//  UILabel+Extension.swift
//  NetWork
//
//  Created by Delin Meng 孟德林 on 2018/9/21.
//  Copyright © 2018年 Delin Meng 孟德林. All rights reserved.
//

import UIKit

extension UILabel {

    /// 根据宽度算出共多少行
    ///
    /// - Parameters:
    ///   - width: 文本宽度，默认为self的width
    ///   - text:  输入的文本
    /// - Returns: 返回的文本
    func needNumberOfLines(width:CGFloat? = nil,text: String? = nil) -> Int {
        let string = (text ?? self.text ?? "") as NSString
        let realWidth = width ?? self.bounds.width
        let font = self.font ?? UIFont.systemFont(ofSize: 14)
        let attributes = [NSAttributedStringKey.font: font]
        let size = CGSize(width:realWidth , height: CGFloat.greatestFiniteMagnitude)
        let labelSize = string.boundingRect(with: size, options: .usesLineFragmentOrigin, attributes: attributes, context: nil)

        return Int(ceil(labelSize.height / font.lineHeight))
    }


    /// 截取多少行的文本
    ///
    /// - Parameters:
    ///   - atString: 原始数据文本
    ///   - maxNumberOfLines: 截取的最大行数
    /// - Returns:
    func truncateText(atString: String, maxNumberOfLines: Int) -> String {
        guard let text = text else { return "" }

        if needNumberOfLines() <= maxNumberOfLines || text.range(of: atString) == nil {
            return text
        }

        let truncatedString = NSMutableString(string: text)
        var range = truncatedString.range(of: atString)
        range.length = 1

        while needNumberOfLines(text: truncatedString as String) > maxNumberOfLines && range.location > 0 {
            range.location -= 1
            truncatedString.deleteCharacters(in: range)
        }

        return truncatedString as String
    }
}


/// 扩大响应区域
class HTLabel:UILabel {

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        var nbouns = self.bounds
        nbouns = nbouns.insetBy(dx: -30, dy: -30)
        nbouns = nbouns.offsetBy(dx: 10, dy: 10)
        return nbouns.contains(point) ? self : nil
    }

}
